<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="en">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="scheme,continuation" />










<meta name="description" content="《The Scheme Programming Language, 4th Edition》中给出了dynamic-wind函数的一种实现，可以给不提供底层dynamic-wind支持的Scheme实现加入这个功能：">
<meta name="keywords" content="scheme,continuation">
<meta property="og:type" content="article">
<meta property="og:title" content="dynamic-wind的实现">
<meta property="og:url" content="https://arucil.github.io/2017/dynamic-wind-implementation/index.html">
<meta property="og:site_name" content="Plodsoft&#39;s Blog">
<meta property="og:description" content="《The Scheme Programming Language, 4th Edition》中给出了dynamic-wind函数的一种实现，可以给不提供底层dynamic-wind支持的Scheme实现加入这个功能：">
<meta property="og:locale" content="en">
<meta property="og:updated_time" content="2017-12-20T07:41:43.539Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="dynamic-wind的实现">
<meta name="twitter:description" content="《The Scheme Programming Language, 4th Edition》中给出了dynamic-wind函数的一种实现，可以给不提供底层dynamic-wind支持的Scheme实现加入这个功能：">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.3',
    sidebar: {"position":"left","display":"always","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://arucil.github.io/2017/dynamic-wind-implementation/"/>





  <title>dynamic-wind的实现 | Plodsoft's Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Plodsoft's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">Programming Language Enthusiast</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-games">
          <a href="/games" rel="section">
            
            Games
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://arucil.github.io/2017/dynamic-wind-implementation/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Plodsoft">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://avatars0.githubusercontent.com/u/5410312?v=4&s=460">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Plodsoft's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">dynamic-wind的实现</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2017-12-20T00:00:00+08:00">
                2017-12-20
              </time>
            

            

            
          </span>

          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2017/dynamic-wind-implementation/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count"
                        data-disqus-identifier="2017/dynamic-wind-implementation/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><em>《The Scheme Programming Language, 4th Edition》</em>中给出了<code>dynamic-wind</code>函数的<a href="https://www.scheme.com/tspl4/control.html#./control:h6" target="_blank" rel="external">一种实现</a>，可以给不提供底层<code>dynamic-wind</code>支持的Scheme实现加入这个功能：<br><a id="more"></a><br><figure class="highlight scheme"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div></pre></td><td class="code"><pre><div class="line">(<span class="name">library</span> (<span class="name"><span class="builtin-name">dynamic-wind</span></span>)</div><div class="line">  (<span class="name">export</span> dynamic-wind call/cc</div><div class="line">    (<span class="name"><span class="builtin-name">rename</span></span> (<span class="name"><span class="builtin-name">call/cc</span></span> call-with-current-continuation)))</div><div class="line">  (<span class="name"><span class="builtin-name">import</span></span> (<span class="name"><span class="builtin-name">rename</span></span> (<span class="name">except</span> (<span class="name">rnrs</span>) dynamic-wind) (<span class="name"><span class="builtin-name">call/cc</span></span> rnrs:call/cc))) </div><div class="line"></div><div class="line">  (<span class="name"><span class="builtin-name">define</span></span> winders '()) </div><div class="line"></div><div class="line">  (<span class="name"><span class="builtin-name">define</span></span> common-tail</div><div class="line">    (<span class="name"><span class="builtin-name">lambda</span></span> (x y)</div><div class="line">      (<span class="name"><span class="builtin-name">let</span></span> ([<span class="name">lx</span> (<span class="name"><span class="builtin-name">length</span></span> x)] [<span class="name">ly</span> (<span class="name"><span class="builtin-name">length</span></span> y)])</div><div class="line">        (<span class="name"><span class="builtin-name">do</span></span> ([<span class="name">x</span> (<span class="name"><span class="builtin-name">if</span></span> (<span class="name"><span class="builtin-name">&gt;</span></span> lx ly) (<span class="name"><span class="builtin-name">list-tail</span></span> x (<span class="name"><span class="builtin-name">-</span></span> lx ly)) x) (<span class="name"><span class="builtin-name">cdr</span></span> x)]</div><div class="line">             [<span class="name">y</span> (<span class="name"><span class="builtin-name">if</span></span> (<span class="name"><span class="builtin-name">&gt;</span></span> ly lx) (<span class="name"><span class="builtin-name">list-tail</span></span> y (<span class="name"><span class="builtin-name">-</span></span> ly lx)) y) (<span class="name"><span class="builtin-name">cdr</span></span> y)])</div><div class="line">            ((<span class="name"><span class="builtin-name">eq?</span></span> x y) x))))) </div><div class="line"></div><div class="line">  (<span class="name"><span class="builtin-name">define</span></span> do-wind</div><div class="line">    (<span class="name"><span class="builtin-name">lambda</span></span> (new)</div><div class="line">      (<span class="name"><span class="builtin-name">let</span></span> ([<span class="name">tail</span> (<span class="name">common-tail</span> new winders)])</div><div class="line">        (<span class="name"><span class="builtin-name">let</span></span> f ([<span class="name">ls</span> winders])</div><div class="line">          (<span class="name"><span class="builtin-name">if</span></span> (<span class="name"><span class="builtin-name">not</span></span> (<span class="name"><span class="builtin-name">eq?</span></span> ls tail))</div><div class="line">              (<span class="name"><span class="builtin-name">begin</span></span></div><div class="line">                (<span class="name"><span class="builtin-name">set!</span></span> winders (<span class="name"><span class="builtin-name">cdr</span></span> ls))</div><div class="line">                ((<span class="name"><span class="builtin-name">cdar</span></span> ls))</div><div class="line">                (<span class="name">f</span> (<span class="name"><span class="builtin-name">cdr</span></span> ls)))))</div><div class="line">        (<span class="name"><span class="builtin-name">let</span></span> f ([<span class="name">ls</span> new])</div><div class="line">          (<span class="name"><span class="builtin-name">if</span></span> (<span class="name"><span class="builtin-name">not</span></span> (<span class="name"><span class="builtin-name">eq?</span></span> ls tail))</div><div class="line">              (<span class="name"><span class="builtin-name">begin</span></span></div><div class="line">                (<span class="name">f</span> (<span class="name"><span class="builtin-name">cdr</span></span> ls))</div><div class="line">                ((<span class="name"><span class="builtin-name">caar</span></span> ls))</div><div class="line">                (<span class="name"><span class="builtin-name">set!</span></span> winders ls)))))))</div><div class="line"></div><div class="line">  (<span class="name"><span class="builtin-name">define</span></span> call/cc</div><div class="line">    (<span class="name"><span class="builtin-name">lambda</span></span> (f)</div><div class="line">      (<span class="name">rnrs:call/cc</span></div><div class="line">        (<span class="name"><span class="builtin-name">lambda</span></span> (k)</div><div class="line">          (<span class="name">f</span> (<span class="name"><span class="builtin-name">let</span></span> ([<span class="name">save</span> winders])</div><div class="line">               (<span class="name"><span class="builtin-name">lambda</span></span> (x)</div><div class="line">                 (<span class="name"><span class="builtin-name">unless</span></span> (<span class="name"><span class="builtin-name">eq?</span></span> save winders) (<span class="name">do-wind</span> save))</div><div class="line">                 (<span class="name">k</span> x)))))))) </div><div class="line"></div><div class="line">  (<span class="name"><span class="builtin-name">define</span></span> dynamic-wind</div><div class="line">    (<span class="name"><span class="builtin-name">lambda</span></span> (in body out)</div><div class="line">      (<span class="name">in</span>)</div><div class="line">      (<span class="name"><span class="builtin-name">set!</span></span> winders (<span class="name"><span class="builtin-name">cons</span></span> (<span class="name"><span class="builtin-name">cons</span></span> in out) winders))</div><div class="line">      (<span class="name"><span class="builtin-name">let-values</span></span> ([<span class="name">ans*</span> (<span class="name">body</span>)])</div><div class="line">        (<span class="name"><span class="builtin-name">set!</span></span> winders (<span class="name"><span class="builtin-name">cdr</span></span> winders))</div><div class="line">        (<span class="name">out</span>)</div><div class="line">        (<span class="name"><span class="builtin-name">apply</span></span> values ans*)))))</div></pre></td></tr></table></figure></p>
<p>主要的idea是维护一个全局winder链表，其中每个winder由传入<code>dynamic-wind</code>函数的<code>in</code>和<code>out</code>两个thunk组成。<br>上面的代码修改了<code>call/cc</code>的定义，新的<code>call/cc</code>会捕获当前的winder链表（称为<code>save</code>），在后续的代码调用<code>call/cc</code>生成的continuation之前，首先从调用点的winder链表（称为<code>winders</code>）头部依次执行<code>out thunk</code>，直到到达<code>winders</code>和<code>save</code>链表的公共部分，然后开始依次执行<code>save</code>链表的<code>in thunk</code>。<br>注意在<code>do-wind</code>函数中，在调用<code>in/out thunk</code>时会同步更新<code>winders</code>全局变量，这样能保证位于<code>in/out thunk</code>中的<code>call/cc</code>能够正确捕获当前的winder链表。<br>Scheme48使用了另一种<code>dynamic-wind</code>的<a href="https://www.cs.hmc.edu/~fleck/envision/scheme48/meeting/node7.html" target="_blank" rel="external">实现</a>，也是维护一个全局winder链表，<code>dynamic-wind</code>/ continuation的调用会不断翻转这个链表。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Scheme/" rel="tag"># Scheme</a>
          
            <a href="/tags/Continuation/" rel="tag"># Continuation</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/r5rs-macro-pattern-language/" rel="next" title="Implementing R5RS's Macro System: Pattern Language">
                <i class="fa fa-chevron-left"></i> Implementing R5RS's Macro System: Pattern Language
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/cps-transformer-implementation/" rel="prev" title="CPS Transformer的实现">
                CPS Transformer的实现 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>
  


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="https://avatars0.githubusercontent.com/u/5410312?v=4&s=460"
                alt="Plodsoft" />
            
              <p class="site-author-name" itemprop="name">Plodsoft</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">4</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          

          <div class="links-of-author motion-element">
            
          </div>

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Plodsoft</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.3</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.3"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>



  


  

    
      <script id="dsq-count-scr" src="https://plodsoft.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'https://arucil.github.io/2017/dynamic-wind-implementation/';
          this.page.identifier = '2017/dynamic-wind-implementation/';
          this.page.title = 'dynamic-wind的实现';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://plodsoft.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  










  





  

  

  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
